package com.canbot.u05.activity.shoppingGuide.merchandiseShoppingGuide;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.adapter.MerchandiseAdapter;
import com.canbot.u05.bean.Merchandise;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.EditTextDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 商品信息设置界面
 */
public class MerchandiseActivity extends BaseActivityNoTitle implements MerchandiseAdapter.MerchandiseOnclickListner {

        private static final String TAG = "MerchandiseActivity";

        private static final int NET_ERROR = 1;

        private Button btnAdd, btnDelete;

        private RecyclerView mRecyclerView;

        private List<Merchandise> mList;

        private MerchandiseAdapter adapter;

        private int currentPosition;

        private Dialog dialogLoading;

        private EditTextDialog editTextDialog;

        private String title;

        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        switch (msg.what) {
                                case NET_ERROR:
                                        ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.network_error));
                                        break;
                        }
                }
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_merchandise);


                setViews();
                initData();
        }

        private void setViews() {
                btnDelete = (Button) findViewById(R.id.btn_delete);
                btnAdd = (Button) findViewById(R.id.btn_add);
                mRecyclerView = (RecyclerView) findViewById(R.id.listView);
        }

        /**
         * 获取数据源
         */
        private void initData() {
//        mList = new ArrayList<>();
//        Merchandise m1 = new Merchandise();
//        m1.setId("1");
//        m1.setTitle("四室一厅");
//        Merchandise m2 = new Merchandise();
//        m1.setId("2");
//        m1.setTitle("三室一厅");
//
//        mList.add(m1);
//        mList.add(m2);
//        //设置适配
//                    setAdapter();
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                mList = new ArrayList<>();
                //获取数据
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<List<Merchandise>> allAction = salesApi.getAllMerchandise();

                allAction.enqueue(new Callback<List<Merchandise>>() {
                        @Override
                        public void onResponse(Call<List<Merchandise>> call, Response<List<Merchandise>> response) {
                                Message message = Message.obtain();
                                if (response.body() != null) {
                                        Logger.e(TAG, "所有商品数据" + response.body().toString());
                                        List<Merchandise> infos = response.body();
                                        if (mList.size()>0){
                                                mList.clear();
                                        }
                                        mList.addAll(infos);

                                        //设置适配
                                        setAdapter();
                                }
                                else {
//                    handler.sendMessage(message);
                                }
                                LoadingDialogUtils.closeDialog(dialogLoading);
                        }

                        @Override
                        public void onFailure(Call<List<Merchandise>> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                mHandler.sendEmptyMessage(NET_ERROR);
                        }
                });
        }

        private void setAdapter() {
                mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                adapter = new MerchandiseAdapter(this, mList,mRecyclerView);
                mRecyclerView.setAdapter(adapter);
                adapter.setListener(this);
                DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,LinearLayoutManager.VERTICAL);
                dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.shape_custom_divider));
                mRecyclerView.addItemDecoration(dividerItemDecoration);
        }

        /**
         * 添加键
         *
         * @param view
         */
        public void add(View view) {
                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.SHOPPING_GUIDE_DIR + "merchandise/spmmts_spdg_u05_001.wav");
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }
                //弹出窗口  添加商品名称
                editTextDialog = new EditTextDialog(MerchandiseActivity.this);
                editTextDialog.setTitle("命名");
                editTextDialog.setOnNegativeListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                editTextDialog.dismiss();
                        }
                });
                editTextDialog.setOnPositiveListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                title = editTextDialog.getEditText().getText().toString();
                                if (TextUtils.isEmpty(title.trim())){
                                        ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.please_first_named));
                                        return;
                                }
                                Logger.e(TAG, "title = " + title);
                                //重复命名提示
                                for (int i = 0;i<mList.size();i++ ){
                                        if (mList.get(i).getTitle().equals(title.trim())){
                                                ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.please_rename));
                                                return;
                                        }
                                }
                                editTextDialog.dismiss();
                                //跳转设置问题界面
                                Intent intent = new Intent(MerchandiseActivity.this, EditMerchandiseActivity.class);
                                intent.putExtra("title", title);
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                        }
                });
                editTextDialog.show();
        }

        /**
         * 返回键
         *
         * @param view
         */
        public void back(View view) {
                finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        @Override
        public void rename() {
                //重命名
                Merchandise merchandise = mList.get(currentPosition);
                Logger.e(TAG, "重命名操作 rename() merchandise == " + merchandise.toString());
                renameDialog(merchandise);
        }

        @Override
        public void edit() {
                //修改商品内容
                //删除
                Merchandise merchandise = mList.get(currentPosition);
                String data = JSON.toJSONString(merchandise);
                Logger.e(TAG, "修改商品内容 edit()  id == " + mList.get(currentPosition).getId());
                Logger.e(TAG, "修改商品内容 edit()  data== " + data);
                //跳转修改内容界面
                Intent intent = new Intent(MerchandiseActivity.this, EditMerchandiseActivity.class);
                intent.putExtra("isEdit", true);
                intent.putExtra("data", data);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);

        }

        @Override
        public void del() {
                //删除
                String id = mList.get(currentPosition).getId();
                Logger.e(TAG, "删除操作 del()  id == " + id);
                delDataFromPad(id);
        }

        @Override
        public void showPopuwindow(int position) {
                currentPosition = position;
        }

        /**
         * 重命名
         */
        private void renameDialog(final Merchandise merchandise) {
                //弹出窗口  重命名商品名称
                editTextDialog = new EditTextDialog(MerchandiseActivity.this);
                editTextDialog.setTitle("重命名");
                editTextDialog.setOnNegativeListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                editTextDialog.dismiss();
                        }
                });
                editTextDialog.setOnPositiveListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                title = editTextDialog.getEditText().getText().toString();
                                if (TextUtils.isEmpty(title.trim())){
                                        ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.please_first_named));
                                        return;
                                }
                                Logger.e(TAG, "title = " + title);
                                //重复命名提示
                                for (int i = 0;i<mList.size();i++ ){
                                        if (mList.get(i).getTitle().equals(title.trim())){
                                                ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.please_rename));
                                                return;
                                        }
                                }
                                Logger.e(TAG, "重命名title = " + title);
                                //上传数据
                                merchandise.setTitle(title);
                                commitToPad(merchandise);
                                editTextDialog.dismiss();
                        }
                });
                editTextDialog.show();
        }



        private void commitToPad(final Merchandise merchandise) {
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this,getString(R.string.data_upload));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                String values = JSON.toJSONString(merchandise);
                Logger.e(TAG, "上传数据" + values);
                Call<String> call = salesApi.editMerchandise(values);

                call.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                if (response.body() != null) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        String body = response.body();
                                        Logger.e(TAG, "网络返回的数据" + body + "");
                                        mList.get(currentPosition).setTitle(merchandise.getTitle());
                                        adapter.notifyDataSetChanged();
//                    initData();
                                }
                                else {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                t.fillInStackTrace();
                                Logger.e(TAG, "网络返回的数据错误信息 " + call.toString());
                                ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.submit_failure));
                        }
                });
        }


        /**
         * 删除头部数据
         *
         * @param id
         */
        private void delDataFromPad(final String id) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.delete));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> url = salesApi.delMerchandise(id + "");
                url.enqueue(new Callback<String>() {

                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                Logger.e(TAG, "删除数据返回值" + response.body());
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                if (!TextUtils.isEmpty(response.body())) {
                                        ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.deleted_successfully));
                                        for (int i = 0; i < mList.size(); i++) {
                                                Merchandise merchandise = mList.get(i);
                                                String merchandiseId = merchandise.getId();
                                                if (merchandiseId.equals(id)) {
                                                        mList.remove(i);
                                                        break;
                                                }
                                        }
                                        adapter.notifyDataSetChanged();

                                }
                                else {
                                        ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.delete_failed));
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(MerchandiseActivity.this).showText(getString(R.string.delete_failed));
                        }
                });
        }


        private static final int TIMEOUT = 100;//超时时间100s

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

        @Override
        protected void onDestroy() {
                if (dialogLoading != null){
                        dialogLoading.dismiss();
                }
                super.onDestroy();
        }
}
